<?php
/**
 * User: hjd-yao
 * Date: 2019/5/10
 * Time: 10:26
 */

namespace App\Http\Controllers\Stats;


use App\Exports\DataExport;
use App\Helpers\Search;
use App\Helpers\SelfEncrypt;
use App\Http\Controllers\BackendController;
use App\Models\Bonus\BonusPoolsModel;
use App\Models\PlatFinanceModel;
use App\Models\Shop\ShopGoodsTrusteeshipModel;
use App\Models\Shop\UserCouponModel;
use Carbon\Carbon;
use DC\UserCenter\Models\UserBaseModel;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PlatStatsController extends BackendController
{

    /**
     * @title 财务统计
     * @return View
     */
    public function countData()
    {
        $rg_count = PlatFinanceModel::selectRaw('IFNULL(sum(`income`),0) as inData,IFNULL(sum(`expend`),0) as outData,IFNULL(sum(`total_rg`),0) as total_rg,IFNULL(sum(`count_rg`),0) as count_rg')->first();

        if (!isset($rg_count['inData'])) {
            $rg_count['inData']=0;
        }
        if (!isset($rg_count['outData'])) {
            $rg_count['outData']=0;
        }

        $rg_count['surplus'] = sprintf("%0.2f", $rg_count['inData']-$rg_count['outData']);

        if($rg_count['inData'] == 0){
            $rg_count['out_rate'] = 100.00;
        }else{
            $rg_count['out_rate'] = round($rg_count['outData']/$rg_count['inData'],4)*100;
        }

        $today = Carbon::today()->timestamp;
        $rg_today = PlatFinanceModel::firstOrCreate(['date'=>$today]);


        $str = "FROM_UNIXTIME(date,'%Y-%m-%d') as e_date,";
        $str.="sum( fact_income ) indata ,sum(fact_expend) outdata ";
        $list = PlatFinanceModel::select(DB::raw("{$str}"))
            ->whereBetween('date',['-15 day',time()])
            ->groupBy(['e_date'])->take(15)->orderBY('date','desc')
            ->get();

        if($list){
            foreach ($list as &$v){
                $v['surplus'] = sprintf("%0.2f", $v['indata']-$v['outdata']);
                if($v['indata'] == 0){
                    $v['out_rate'] = 100.00;
                }else{
                    $v['out_rate'] = round($v['outdata']/$v['indata'],4)*100;
                }
            }
        }else{
            $list = [];
        }
        return view('backend::stats.plat.index',[
            'page_title'=>'财务统计',
            'rg_count'=>$rg_count,
            'rg_today'=>$rg_today,
            'list'=>$list
        ]);
    }

    /**
     * @title 充值趋势图
     * @return JsonResponse
     */
    public function chartRgData()
    {
        $list = PlatFinanceModel::where('date','>=',Carbon::today()->subDay(15)->timestamp)
            ->select(['total_rg','count_rg','date'])->get();

        $num = array_column($list->toArray(),'count_rg','date');
        $rg_money = array_column($list->toArray(),'total_rg','date');

        $number = $money = $dates = [];
        for($i=0; $i < 15; $i++){
            $date = Carbon::today()->subDay(14-$i);
            $dates[] = $date->format('Y/m/d');
            $number[] = $num[$date->timestamp] ?? 0;
            $money[] = $rg_money[$date->timestamp] ?? 0;

        }
        return response()->json([
            'status'=>1,
            'data'=>[
                'dates'=>$dates,
                'num'=>$number,
                'money'=>$money,
            ]
        ]);
    }


    /**
     * @title 提冲比
     * @param Request $request
     * @return View
     */
    public function ctRatio(Request $request)
    {
        $search = Search::make($request)->bindModel(UserWalletModel::with(['user'])->has('user'))
            ->input('user_number','编号')
            ->input('name','姓名','',['field'=>'member_id'])
            ->input('phone','手机号','',['field'=>'member_id'])
            ->input('rg_ratio','提现充值比例大于','',['symbol'=>'>=','field'=>['total_wd','total_rg']])
            ->bindSearchData()->relationModel(['name'=>function($value){
                return UserBaseModel::where('real_name',$value)->pluck('member_id')->toArray();
            },'phone'=>function($value){
                return UserBaseModel::where('user_phone',$value)->value('member_id');
            }]);
        $model = $search->where();
        if($request->has('rg_ratio')){
            $model->Where(function ($query) use ($request){
                    $query->where('total_rg', '>', 0)
                        ->whereRaw('`total_wd`/`total_rg`>=?',[abs($request->input('rg_ratio'))/100]);
                })->orWhere([
                    ['total_wd','>=',abs($request->input('rg_ratio'))],
                    ['total_rg','=',0]
                ]);
        }
        $list = $model->paginate($this->getPerPageNum());

        return view('backend::stats.plat.ct_ratio',[
            'page_title'=>'会员充值提现统计',
            'list'=>$list,
            'search_tpl'=>$search
        ]);
    }

    /**
     * @title 导出黑名单会员
     * @param Request $request
     * @return Response|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportCtUser(Request $request)
    {
        $perPage = $request->input('per');
        $user_id = $request->input('user_id');
        $user_id = is_array($user_id)?$user_id:str2arr($user_id);
        $userModel = UserBaseModel::with(['wallet'=>function ($query){
            $query->select(['member_id','money1','total_rg','total_wd']);
        }])->select(['member_id','user_number','real_name','user_phone']);
        if($user_id){
            $userModel = $userModel->whereIn('member_id',$user_id);
        }
        $data = $userModel->forPage($perPage,$this->getPerPageNum())->get();
        //dd($data->toArray());
        return (new DataExport())->setHeadings('会员充提信息',['user_id','会员姓名','联系方式','现金分','累计充值','累计提现','提充比'])
            ->filterData($data,function ($data){
                foreach ($data as $key=>&$item){
                    $item->money1 = $item->wallet->money1;
                    $item->total_rg = $item->wallet->total_rg;
                    $item->total_wd = $item->wallet->total_wd;
                    if($item->wallet->total_rg == 0){
                        $item->rg_ratio = (int)$item->wallet->total_wd*100;
                    }elseif ($item->wallet->total_wd == 0){
                        $item->rg_ratio = 0;
                    }else{
                        $item->rg_ratio = ($item->wallet->total_wd/$item->wallet->total_rg)*100;
                    }
                    unset($item->wallet,$item->member_id);
                }
                return $data;
            })->download('user'.SelfEncrypt::createCode().'.xlsx');
    }

    /**
     * @title 委托统计
     * @return View
     */
    public function countTrusteeship()
    {
        $list = ShopGoodsTrusteeshipModel::where('status','>=',0)->selectRaw('count(*) as num,sum(return_money) as money,status')->groupBy('status')->get();
        return view('backend::stats.plat.trusteeship',[
            'page_title'=>'托管统计',
            'list'=>$list
        ]);
    }

    /**
     * @title 委托趋势
     * @return JsonResponse
     */
    public function chartTg()
    {
        $list = DB::table('tg_stats')->where('dates','>=',Carbon::today()->subDay(15)->timestamp)->get();
        $num1 = $in_num = [];
        $num2 = $out_num=[];

        foreach ($list as $item){
            $dates[] = Carbon::createFromTimestamp($item->dates)->format('Y/m/d');
            $num1[$item->dates] = $item->in_num;
            $num2[$item->dates] = $item->out_num;
        }
        $dates = [];

        for($i=0; $i < 15; $i++){
            $date = Carbon::today()->subDay(14-$i);
            $dates[] = $date->format('Y/m/d');
            $in_num[] = $num1[$date->timestamp] ?? 0;
            $out_num[] = $num2[$date->timestamp] ?? 0;

        }

        return response()->json(['status'=>1,'data'=>[
            'dates'=>$dates,
            'in_num'=>$in_num,
            'out_num'=>$out_num,
        ]]);
    }

    /**
     * @title 提货券统计
     * @param Request $request
     * @return View
     */
    public function countCoupon(Request $request)
    {
        $count = UserCouponModel::has('user')->where('status','>=',0)
            ->selectRaw('count(*) as num,sum(th_face_value) as face_money,sum(th_market_value) as market_money,status')->groupBy('status')->get();

        $search = Search::make($request)->bindModel(UserCouponModel::with('user')->has('user')->where('status','>=',0))
                ->input('user','编号\姓名\手机号','',['field'=>'user_id'])
                ->bindSearchData()->relationModel(['user'=>function($value){
                    return UserBaseModel::where('user_number',$value)->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id');
            }]);
        $list = $search->where()
            ->selectRaw('user_id,count(IF(`status`=0,1,NULL)) as no_num, count(IF(`status`=1,1,NULL)) as has_num, SUM(IF(`status`=0,th_face_value,0)) as no_face_money 
                        ,SUM(IF(`status`=0,th_market_value,0)) as no_market_money 
                        ,SUM(IF(`status`=1,th_face_value,0)) as has_face_money
                            ,SUM(IF(`status`=1,th_market_value,0)) as has_market_money ')
            ->groupBy('user_id')->paginate($this->getPerPageNum());

        return view('backend::stats.plat.coupon',[
            'page_title'=>'提货券统计',
            'list'=>$list,
            'count'=>$count,
            'search_tpl'=>$search
        ]);
    }



    /**
     * @title 奖金池 统计
     * @param Request $request
     * @return View
     */
    public function BonusPools(Request $request){

        $model = new BonusPoolsModel();
        // 本周开始 结束 时间
        $start_week = Carbon::now()->startOfWeek()->timestamp;
        $end_week = Carbon::now()->endOfWeek()->timestamp;
        // 分红池
        $bonus_pools_one = $model::where('change_type',1)->selectRaw('IFNULL(sum(`income`),0) as inData,IFNULL(sum(`expend`),0) as outData')->first();

        if (!isset($bonus_pools_one['inData'])) {
            $bonus_pools_one['inData']=0;
        }
        if (!isset($bonus_pools_one['outData'])) {
            $bonus_pools_one['outData']=0;
        }

        $bonus_pools_one['surplus'] = sprintf("%0.2f", $bonus_pools_one['inData']-$bonus_pools_one['outData']);

        if($bonus_pools_one['inData'] == 0){
            $bonus_pools_one['out_rate'] = 100.00;
        }else{
            $bonus_pools_one['out_rate'] = round($bonus_pools_one['outData']/$bonus_pools_one['inData'],4)*100;
        }
        $one_oneWeek_income = $model::where('change_type',1) ->whereBetween('date',[$start_week,$end_week])->sum('income') ?? 0;
        $bonus_pools_one['oneWeek_income']=$one_oneWeek_income ;

        // 股东分红
        $bonus_pools_two = $model::where('change_type',2)->selectRaw('IFNULL(sum(`income`),0) as inData,IFNULL(sum(`expend`),0) as outData')->first();

        if (!isset($bonus_pools_two['inData'])) {
            $bonus_pools_two['inData']=0;
        }
        if (!isset($bonus_pools_two['outData'])) {
            $bonus_pools_two['outData']=0;
        }

        $bonus_pools_two['surplus'] = sprintf("%0.2f", $bonus_pools_two['inData']-$bonus_pools_two['outData']);

        if($bonus_pools_two['inData'] == 0){
            $bonus_pools_two['out_rate'] = 100.00;
        }else{
            $bonus_pools_two['out_rate'] = round($bonus_pools_two['outData']/$bonus_pools_two['inData'],4)*100;
        }
        $two_oneWeek_income = $model::where('change_type',2) ->whereBetween('date',[$start_week,$end_week])->sum('income') ?? 0;
        $bonus_pools_two['oneWeek_income']=$two_oneWeek_income ;


        // 福利池
        $bonus_pools_three = $model::where('change_type',3)->selectRaw('IFNULL(sum(`income`),0) as inData,IFNULL(sum(`expend`),0) as outData')->first();

        if (!isset($bonus_pools_three['inData'])) {
            $bonus_pools_three['inData']=0;
        }

        //合伙人
        $bonus_pools_four = $model::where('change_type',4)->selectRaw('IFNULL(sum(`income`),0) as inData,IFNULL(sum(`expend`),0) as outData')->first();

        if (!isset($bonus_pools_four['inData'])) {
            $bonus_pools_four['inData']=0;
        }

        if (!isset($bonus_pools_four['outData'])) {
            $bonus_pools_four['outData']=0;
        }

        $bonus_pools_four['surplus'] = sprintf("%0.2f", $bonus_pools_four['inData']-$bonus_pools_four['outData']);

        if($bonus_pools_four['inData'] == 0){
            $bonus_pools_four['out_rate'] = 100.00;
        }else{
            $bonus_pools_four['out_rate'] = round($bonus_pools_four['outData']/$bonus_pools_four['inData'],4)*100;
        }

        $start_month =Carbon::now()->startOfMonth()->timestamp;
        $end_month=Carbon::now()->endOfMonth()->timestamp;
        $four_oneMonth_income = $model::where('change_type',4) ->whereBetween('date',[$start_month,$end_month])->sum('income') ?? 0;
        $bonus_pools_four['oneMonth_income']=$four_oneMonth_income ;

        $people_num = UserBaseModel::init()->where('status',1)->where('is_partner',1)->count() ?? 0;
        $bonus_pools_four['partner_num'] = $people_num ;

        return view('backend::stats.plat.bonus_pools',[
            'page_title'=>'奖金池',
            'bonus_pools_one'=>$bonus_pools_one,
            'bonus_pools_two'=>$bonus_pools_two,
            'bonus_pools_three'=>$bonus_pools_three,
            'bonus_pools_four'=>$bonus_pools_four,
        ]);

    }

    /**
     * @title 奖金池详细信息
     * @param $type
     * @param Request $request
     * @return View
     */
    public function BonusPoolsList(Request $request,$type){

        $search = Search::make($request)->bindModel(new BonusPoolsModel())
            ->time('date','统计时间')
            ->bindSearchData();

        $model = $search->where();

        $list = $model->where('change_type',$type)->orderBy('date','desc')->paginate($this->getPerPageNum());

        if($list){
            foreach ($list as &$v){
                $v['surplus'] = sprintf("%0.2f", $v['income']-$v['expend']);
                if($v['income'] == 0){
                    $v['out_rate'] = 100.00;
                }else{
                    $v['out_rate'] = round(($v['expend']/$v['income']),4) * 100;
                }
            }
        }else{
            $list = [];
        }

        return view('backend::stats.plat.bonus_pools_list',[
            'page_title'=>'信息统计',
            'list'=>$list,
            'search_tpl'=>$search,
            'type'=>$type
        ]);
    }
}